﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
namespace XHXTools
{
    /// <summary>
    /// ftp具体操作类
    /// </summary>
    public class FtpTool
    {
        private FtpNetModel fnm { get; set; }
        internal FtpTool(FtpNetModel _fnm)
        {
            fnm = _fnm;
        }

        #region  上传
        /// <summary>
        /// 上传文件（只试用上传小文件对象）——[含IP][含端口][含路径、文件名]
        /// </summary>
        /// <param name="address">ftp全路径地址</param>
        /// <returns>上传成功返回的字符串包含 “226”</returns>
        internal int FtpUploadFile(string address)
        {
            try
            {
                //初始化地址路径
                // Uri uri = new Uri(address);
                //连接初始化FTP
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(address);

                //指定连接用户凭据
                request.Credentials = fnm.GetNetwork;

                request.KeepAlive = true;

                //指定当前操作是上传文件
                request.Method = WebRequestMethods.Ftp.UploadFile;


                Stream stream = fnm.IFile.OpenReadStream();
                byte[] bt = new byte[fnm.IFile.Length];
                stream.Read(bt, 0, (int)fnm.IFile.Length);
                using (Stream st = request.GetRequestStream())
                {
                    st.Write(bt, 0, (int)fnm.IFile.Length);
                }
                stream.Close();
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();

                int code = (int)response.StatusCode;

                return code;
            }
            catch (WebException ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 上传文件(字节流)[含IP][含端口][含路径、文件名]
        /// </summary>
        /// <param name="bt">文件流</param>
        /// <param name="address">ftp地址全路径</param>
        /// <returns>上传成功返回的字符串包含 “226”</returns>
        internal string FtpUploadFile(byte[] bt, string address)
        {
            try
            {
                //初始化地址路径
                Uri uri = new Uri(address);
                //连接初始化FTP
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
                //指定连接用户凭据
                request.Credentials = fnm.GetNetwork;

                request.KeepAlive = false;

                //指定当前操作是上传文件
                request.Method = WebRequestMethods.Ftp.UploadFile;

                using (Stream st = request.GetRequestStream())
                {
                    st.Write(bt, 0, bt.Length);
                }
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();

                string sta = response.StatusDescription;

                return sta;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 下载
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="address">路径</param>
        /// <returns>返回Stream数据流</returns>
        internal Stream FtpDownloadFile(string address)
        {
            try
            {
                //连接初始化FTP
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(address);
                //指定连接用户凭据
                request.Credentials = fnm.GetNetwork;
                request.KeepAlive = true;

                //指定当前操作是下载文件
                request.Method = WebRequestMethods.Ftp.DownloadFile;

                FtpWebResponse response = (FtpWebResponse)request.GetResponse();

                Stream stream = response.GetResponseStream();

                return stream;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 删除
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="address">路径</param>
        internal int FtpDeleteFile(string address)
        {
            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(address);
                //指定连接用户凭据
                request.Credentials = fnm.GetNetwork;
                //指定当前操作是删除文件
                request.Method = WebRequestMethods.Ftp.DeleteFile;
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                int code = (int)response.StatusCode;
                return code;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 删除目录
        /// </summary>
        /// <param name="address">路径</param>
        internal void FtpDeleteFolder(string address)
        {
            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(address);
                //指定连接用户凭据
                request.Credentials = fnm.GetNetwork;
                //指定当前操作是删除目录
                request.Method = WebRequestMethods.Ftp.RemoveDirectory;
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        #region 文件或目录是否存在
        /// <summary>
        /// 判断目录(或文件)是否存在
        /// </summary>
        /// <param name="address">路径</param>
        /// <param name="folderOrFile">文件或目录</param>
        /// <returns>存在此目录返回true，不存在返回false</returns>
        internal bool IsExistsFolder(string address, string folderOrFile)
        {
            List<string> list = new List<string>();
            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(address);
                //指定连接用户凭据
                request.Credentials = fnm.GetNetwork;
                request.Method = WebRequestMethods.Ftp.ListDirectory;//指定当前操作是获取ftp简略目录列表
                WebResponse response = request.GetResponse();//接收ftp的响应
                StreamReader streamReader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);//把ftp响应转为字节流
                string line = streamReader.ReadLine();//读取一行数据
                while (line != null)
                {
                    list.Add(line);
                    line = streamReader.ReadLine();
                }
                address = $"{address}/{folderOrFile}";
                foreach (var item in list)
                {
                    //判断是否存在ftp中
                    if (address.Contains(item))
                    {
                        return true;
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        #region 移动或改名

        /// <summary>
        /// 移动  或   改名
        /// </summary>
        /// <param name="oldAddress">旧目录 [含IP和端口]</param>
        /// <param name="newAddress">新目录 [不含IP和端口]</param>
        /// <returns></returns>
        internal int MoveOrRename(string oldAddress, string newAddress)
        {
            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(oldAddress);
                request.Credentials = fnm.GetNetwork;
                request.Method = WebRequestMethods.Ftp.Rename;
                //Uri u = new Uri(newAddress);

                request.RenameTo = newAddress;

                FtpWebResponse response = (FtpWebResponse)request.GetResponse();

                Stream stream = response.GetResponseStream();
                if (stream != null) stream.Close();
                int code = (int)response.StatusCode;
                response.Close();
                request = null;
                return code;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        #region 获取列表


        /// <summary>
        /// 获取文件列表——[含IP][含端口][不含文件名]
        /// </summary>
        /// <param name="address">ftp地址——[含IP][含端口][不含文件名]</param>
        /// <returns></returns>
        internal List<string> GetFileList(string address)
        {
            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(address);
                request.Credentials = fnm.GetNetwork;
                request.Method = WebRequestMethods.Ftp.ListDirectory;

                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                StreamReader streamReader = new StreamReader(response.GetResponseStream());

                List<string> list = new List<string>();
                string line = streamReader.ReadLine();
                while (line != null)
                {
                    list.Add(line);
                    line = streamReader.ReadLine();
                }
                return list;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion



        /// <summary>
        /// 获取文件列表——[含IP][含端口][不含文件名]
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        internal object UploadAppend(string address)
        {
            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(address);
                request.Credentials = fnm.GetNetwork;
                request.Method = WebRequestMethods.Ftp.AppendFile;

                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                StreamReader streamReader = new StreamReader(response.GetResponseStream());

                List<string> list = new List<string>();
                string line = streamReader.ReadLine();

                return "";
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

    }
}

